#!/bin/bash

. /etc/nstat.conf

echo "`date` $0 $*" >>/var/log/nstat-firewall.log

IPTABLES()
{
    /sbin/iptables $* || echo "Failed: iptables $*" >&2
}

# человеко-понятные имена цепочек
ct()
{
    if [ $1 -eq 1 ]; then echo "internet"; return; fi
    if [ $1 -eq 2 ]; then echo "local"; return; fi
    if [ $1 -eq 4 ]; then echo "utel"; return; fi
    if [ $1 -eq 5 ]; then echo "miscellaneous"; return; fi
    echo category$1
}

categories="1 2 4"

command=$1

shift

down()
{
    ip=$1
    for i in $categories
    do
        cn=`ct $i`
        IPTABLES -D "${cn}_in"  -d $ip -j ACCEPT 2>/dev/null || true
        IPTABLES -D "${cn}_in"  -d $ip -j ULOG --ulog-qthreshold 40 --ulog-cprange 100 --ulog-nlgroup 1 --ulog-prefix $i 2>/dev/null || true
        IPTABLES -D "${cn}_out" -s $ip -j ACCEPT 2>/dev/null || true
        IPTABLES -D "${cn}_out" -s $ip -j ULOG --ulog-qthreshold 40 --ulog-cprange 100 --ulog-nlgroup 1 --ulog-prefix $i 2>/dev/null || true
    done
    echo "deleted rules for $ip"
}

up()
{
    ip=$1
    shift
    categories=$*
    for i in $categories
    do
        cn=`ct $i`
        IPTABLES -I "${cn}_in"  -d $ip -j ACCEPT
        IPTABLES -I "${cn}_in"  -d $ip -j ULOG --ulog-qthreshold 40 --ulog-cprange 100 --ulog-nlgroup 1 --ulog-prefix $i
        IPTABLES -I "${cn}_out" -s $ip -j ACCEPT
        IPTABLES -I "${cn}_out" -s $ip -j ULOG --ulog-qthreshold 40 --ulog-cprange 100 --ulog-nlgroup 1 --ulog-prefix $i
    done
    echo "created rules for $ip"
}

channel()
{
    ip=$1
    table=$2
    
    while ip rule del from ${ip} 2>/dev/null; do true; done

    ip rule add from ${ip} unreachable
    ip rule add from ${ip} table $2
    
    for net in ${local_sites}
    do
        ip rule add from ${ip} to ${net} table main
    done
}

case $command in
    reset)
        echo "Resetting firewall:"
        for i in $categories
        do
            for p in "in" "out"
            do
                cn=`ct $i`_${p}
                echo " => ${cn}"
                IPTABLES -N "${cn}" 2>/dev/null || true
                IPTABLES -F "${cn}"
                IPTABLES -A "${cn}" -j REJECT --reject-with icmp-net-prohibited
            done
        done
        ;;
    down)
        down $*
        ;;
    up)
        down $*
        up $*
        ;;
    channel)
        channel $*
        ;;
    *)
        echo "Using:"
        echo "  1) $0 reset"
        echo "  2) $0 up <ip> <category1> <category2>..."
        echo "  3) $0 down <ip>"
        echo "  4) $0 channel <ip> <table>"
        exit 1
esac
